import {
  login,
} from '@/api/data'
import Cookies from 'js-cookie'
const TOKEN_KEY = 'token'
 const getToken = () => {
  const token = Cookies.get(TOKEN_KEY)
  if (token) return token
  else return false
}
const setToken = (token) => {
  Cookies.set(TOKEN_KEY, token, { expires: 1 })
}
export default {
  state: {
    userName: window.sessionStorage.getItem('username'),
    userId: window.sessionStorage.getItem('userid'),
    token: getToken(),
    access: window.sessionStorage.getItem('access'),
    hasGetInfo: window.sessionStorage.getItem('HasGetInfo'),
  },

  mutations: {
    setUserId (state, id) {
      state.userId = id
      window.sessionStorage.setItem('userid', id)
    },
    setUserName (state, name) {
      state.userName = name
      window.sessionStorage.setItem('username', name)
    },
    setAccess (state, access) {
      state.access = access
      window.sessionStorage.setItem('access', JSON.stringify(access))
    },
    setToken (state, token) {
      state.token = token
      setToken(token)
      window.sessionStorage.setItem('token', token)
    },
    setHasGetInfo (state, status) {
      state.hasGetInfo = status
      window.sessionStorage.setItem('HasGetInfo', status)
    }
  },
  getters: {
    messageUnreadCount: state => state.messageUnreadList.length,
    messageReadedCount: state => state.messageReadedList.length,
    messageTrashCount: state => state.messageTrashList.length
  },
  actions: {
    // 登录
    handleLogin ({ commit }, data) {
      return new Promise((resolve, reject) => {
        login(data).then(res => {
          console.log(res)
          const data = res.data
          commit('setToken', data.token)
          commit('setUserName', data.username)
          commit('setUserId', data.userid)
          commit('setAccess', data.access)
          commit('setHasGetInfo', true)
          window.sessionStorage.setItem('username', data.username)
          window.sessionStorage.setItem('userid', data.userid)
          window.sessionStorage.setItem('token', data.token)
          window.sessionStorage.setItem('HasGetInfo', true)
          window.sessionStorage.setItem('access', data.access + '')
          resolve(data)
        }).catch(err => {
          reject(err)
        })
      })
    },
    // 退出登录
    handleLogOut ({ state, commit }) {
      return new Promise((resolve) => {
        sessionStorage.clear()
        commit('setToken', '')
        commit('setAccess', [])
        resolve()
      })
    }, 
  }
}
